local gamelib = require "club.threecard.gamelib"
local slotlib = require "club.threecard.slotlib"
local components = slotlib.require "components"

local slot_system = slotlib.systems.slot_system
local class = gamelib.entitas.class
local Matcher = gamelib.entitas.Matcher
local GroupEvent = gamelib.entitas.GroupEvent

local draw_line_system = class("show_result_system", slot_system)

function draw_line_system:initialize()
    self.context.machine:replace(components.frames_component, {})
end

function draw_line_system:get_trigger()
    return {{Matcher({components.frames_component, components.reel_offset_component}), GroupEvent.ADDED}};
end

function draw_line_system:filter(entity)
    return entity:has(components.frames_component) and entity:has(components.reel_offset_component)
end

local function filter_frame(frames)
    local ret = {}    

    for _, frame in ipairs(frames) do
        if frame.type == slotlib.frame_type.line_hit then
            table.insert(ret, frame);
        end
    end

    return ret;
end

function draw_line_system:execute(entitas)
    if entitas:size() ~= 1 then
        gamelib.log.error("数据错误，结果组件不可能>1")
        return;
    end

    entitas:foreach(function(e)
        local frames = e:get(components.frames_component).frames;
        frames = filter_frame(frames);
        if #frames == 0 then
            return;
        end

        local reel_offsets = e:get(components.reel_offset_component).reel_offsets
        for _, frame in ipairs(frames) do
            local payline = self.ingame.machine.config.paylines[frame.id]
            if payline == nil then
                gamelib.log.error("没有找到赔付线 id:"..frame.id)
                break;
            end

            if #reel_offsets ~= #payline then
                gamelib.log.error("#reel_offsets ~= #payline ->"..gamelib.dump(reel_offsets).."::::"..gamelib.dump(payline))
                break;
            end

            local line_indexes = {};

            for i, value in ipairs(reel_offsets) do
                table.insert(line_indexes, value + payline[i]);
            end

            self.ingame.machine:draw(line_indexes);
            self:wait(0.1);
        end

        self:wait(0.5);
        slotlib.line.clear();
    end)
end

function draw_line_system:tear_down()
    slotlib.line.clear();
end

return draw_line_system